# 练习题- ⽤户登录认证程序
# 要求⽤户输⼊帐号密码进⾏登陆
# ⽤户账号信息保存在⽂件内
# ⽤户密码输⼊错误三次后锁定⽤户，下次再登录，检测到是这个被锁定的⽤户，则依然不允许其它登录，提示已被锁
import hashlib
import os


def read_users(file_path):
    """读取用户信息文件并返回用户数据，格式为字典：{用户名: 哈希密码}"""
    users = {}
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            line = line.strip()
            if not line or ',' not in line:
                continue  # 跳过空行或格式不正确的行
            username, hashed_password = line.strip().split(',')
            users[username] = hashed_password
    return users


def read_locked_users(file_path):
    """读取被锁定用户文件并返回锁定用户集合"""
    locked_users = set()
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            locked_users.add(line.strip())
    return locked_users


def write_locked_user(file_path, username):
    """将锁定用户写入锁定文件"""
    with open(file_path, 'a') as file:
        file.write(username + '\n')


def hash_password(password):
    """返回密码的哈希值"""
    return hashlib.sha256(password.encode('utf-8')).hexdigest()


def authentication(username, password, users, locked_users):
    """进行登录认证"""
    if username in locked_users:
        print("用户已经被锁定，请联系管理员解锁。")
        return False

    if username not in users:
        print("用户名不存在，请检查后再试。")
        return False

    stored_hashed_password = users[username]
    input_hashed_password = hash_password(password)

    if stored_hashed_password == input_hashed_password:
        print("登录成功！")
        return True
    else:
        return False


def are_elements_equal(locked_user_name):
    if len(locked_user_name) != 3:
        return False
    return locked_user_name[0] == locked_user_name[1] == locked_user_name[2]


def main():
    users_file = os.path.join('..', 'tempFile', 'users.txt')
    locked_file = os.path.join('..', 'tempFile', 'locked_users.txt')

    users = read_users(users_file)
    locked_users = read_locked_users(locked_file)

    # 定义一个数组记录锁定的用户名
    locked_user_name = {}
    for attempt in range(3):
        username = input("请输入用户名：")
        password = input("请输入密码：")

        if authentication(username, password, users, locked_users):
            print("登录成功！")
            return

        print(f"密码错误，你还有 {2 - attempt} 次尝试机会。")
        locked_user_name[attempt] = username

    print("密码错误次数过多，账户已锁定。")
    # 判断locked_user_name中三个元素是否都相同
    if are_elements_equal(locked_user_name):
        # 获取locked_user_name中的第一个元素
        write_locked_user(locked_file, locked_user_name.get(0))


if __name__ == "__main__":
    main()
